package com.xbang.util.voucher.imp;

import java.util.Calendar;
import java.util.Date;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.codingrule.CodingRuleFactory;
import com.kingdee.eas.base.codingrule.CodingRuleInfo;
import com.kingdee.eas.base.codingrule.ICodingRule;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.common.client.SysContext;
import com.kingdee.eas.fi.gl.VoucherInfo;
import com.kingdee.util.DateTimeUtils;

/**
 * @author lifetime 2009-2-21
 * 
 */
public class VoucherNumberRead {
	private static VoucherNumberRead instance = new VoucherNumberRead();
	protected CodingRuleInfo codingRuleInfo = null;
	protected int ruleCount = 0;
	protected ICodingRule codingRuleInface;
	private VoucherInfo voucherNumberTemp = new VoucherInfo();
	private int pzhCount = 1;

	public static String read() {
		String number = null;
		try {
			number = instance.readNumber();
		} catch (Exception e) {
			number = "System : " + SysContext.getSysContext().getCurrentUserInfo().getName() + "_"
					+ DateTimeUtils.format(Calendar.getInstance().getTime(), "yyyyMMdd") + "_" + instance.getPzhCount();
		}
		return number;
	}

	private VoucherNumberRead() {
		try {
			this.codingRuleInface = CodingRuleFactory.getRemoteInstance();
			this.codingRuleInfo = getVoucherCodingRule(null);
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (EASBizException e) {
			e.printStackTrace();
		}
	}

	public static CodingRuleInfo getVoucherCodingRule(String orgId) throws EASBizException, BOSException {
		ICodingRule codingRuleInface = CodingRuleFactory.getRemoteInstance();
		if (!BOSUuid.isValid(orgId, true)) {
			orgId = SysContext.getSysContext().getCurrentOrgUnit().getId().toString();
		}
		String oql = "where appOrgUnit = '" + orgId
				+ "' and businessObject = 'com.kingdee.eas.fi.gl.app.Voucher' and isEnabled = 1 and bindingProperty.propertyValue = '" + 0 + "'";
		if (codingRuleInface.exists(oql)) {
			return codingRuleInface.getCodingRuleInfo(oql);
		}
		orgId = SysContext.getSysContext().getCurrentCtrlUnit().getId().toString();
		if (codingRuleInface.exists(oql)) {
			return codingRuleInface.getCodingRuleInfo(oql);
		}
		orgId = "00000000-0000-0000-0000-000000000000CCE7AED4";
		if (codingRuleInface.exists(oql)) {
			return codingRuleInface.getCodingRuleInfo(oql);
		}
		return null;
	}

	protected String readNumber() throws Exception {
		if (this.codingRuleInfo == null) {
			Calendar calendar = Calendar.getInstance();
			Date now = calendar.getTime();
			return DateTimeUtils.format(now, "yyyyMMdd_hhmmss_SSS") + this.ruleCount++;
		}
		return this.codingRuleInface.getNumber(this.voucherNumberTemp, this.codingRuleInfo, false, true);
	}

	private int getPzhCount() {
		return this.pzhCount++;
	}
}